/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pgentity.minigame.freakingeggs;

import db.DBContext;
import db.PGKeys;
import db.RedisKey;
import java.util.List;
import share.PGError;
import share.PGException;
import share.PGHelper;

/**
 *
 * @author Salm
 */
public class FreakingEggs {
    private final String uid;
    private final String token;
    private boolean[] results;

    private FreakingEggs(String uid, String token) {
        this.uid = uid;
        this.token = token;
    }
    
    public static FreakingEggs getFE(String uid, String token)
    {
        RedisKey key = key(uid, token);
        PGException.Assert(DBContext.Redis()
                .exists(key), PGError.INVALID_GAME, "Game not exist");
        
        FreakingEggs fe = new FreakingEggs(uid, token);
        fe.updateFromDB();
        
        return fe;
    }
    
    public static FreakingEggs newFE(String uid,
            String token, boolean[] results)
    {
        RedisKey key = key(uid, token);
        PGException.Assert(!DBContext.Redis()
                .exists(key), PGError.GAME_EXISTED, "Game already existed");
        
        
        String[] arrSResult = new String[results.length];
        int i = 0;
        for (boolean result : results) {
            arrSResult[i++] = String.valueOf(result);
        }
        
        DBContext.Redis().lappend(key, arrSResult);
        DBContext.Redis().expire(key, 600); // 10 minutes
        
        FreakingEggs fe = new FreakingEggs(uid, token);
        fe.results = results;
        
        return fe;
    }
    
    public static void destroy(String uid, String token)
    {
        DBContext.Redis().del(key(uid, token));
    }
    
    public static RedisKey key(String uid, String token)
    {
        return PGKeys.USERS.getChild(uid)
                .getChild(PGKeys.FD_MINIGAME)
                .getChild(PGKeys.FD_FREAKINGEGGS)
                .getChild(token);
    }
    
    private void updateFromDB()
    {
        List<String> data = DBContext.Redis().lgetall(key(uid, token));
        results = new boolean[data.size()];
        
        int i = 0;
        for (String res : data) {
            results[i++] = PGHelper.toBoolean(res);
        }
    }
    
    public boolean resultAt(int i)
    {
        return results[i];
    }
    
    public int nTurn()
    {
        return results.length;
    }
}
